#!/bin/bash
version="V1.0"
echo "The script is $version."
server="http://192.168.2.94:8001/"

function get_newest_ver()
{
	if [ ! -n $1 ];then
		return 1
	fi
	local url=$1

	local verfile=$(basename $0)
	verfile=${verfile%.*}
	wget -q "${url}" -O ".${verfile}_info.txt"
	local newest_ver=0
	while read line
	do
		if [[ $line =~ "HREF=\"/V" ]]
		then
			tmp=${line#*'V'}
			tmp=${tmp%\"*}
			if [ $(expr $tmp \> $newest_ver) -eq 1 ];then
				newest_ver=$tmp
			fi
		fi
	done < ".${verfile}_info.txt"
	rm .${verfile}_info.txt
	echo "$newest_ver"
	return 
}


if [ "$(id -u)" != "0" ]; then
   echo "This script must be run as root!" 1>&2
   exit 1
fi

ps_version="/sys/bus/platform/devices/amba_pl/40000000.axi-bram/"
# if [ ! -d $ps_version ];then
# 	echo "Count not find device"
# 	exit 1
# fi

# sw_version=$(cat ${ps_version}/ps_version) >&2
# if [[ "$sw_version" = "" ]]
# then
# 	echo "error:canot get Image version"
# 	exit 1
# fi

# board=$(cat /proc/device-tree/model) >&2
# if [[ $board =~ "MZ7X" ]]; then
#         board="MZ7X"
#         echo "Current board is MZ7X"
# else
#         echo "Device tree don't have describe as MZ7X"
#         exit 1
# fi
sw_version="1.0.0"
echo "Current driver version is $sw_version."
new=$(get_newest_ver $server)

# if ((version_m > current_m || (version_m == current_m && version_s > current_s))) 
if [ $(expr $new \> $sw_version) -eq 1 ];
then
	echo "The newest version is V$new."
	exit 0
	read -p "Are you want to update to the newest version? [Y/n]" update_sel
	if [[ $update_sel = "Y" ]] || [[ $update_sel = "y" ]] || [[ $update_sel = "" ]]
    then
		echo "Update to V$new"
		if ! mountpoint -q /mnt; then
			mount /dev/mmcblk0p1 /mnt/
		fi

		mv /mnt/devicetree.dtb /mnt/devicetree.dtb.bak
		wget -c "${server}V${new}/devicetree.dtb" -O /mnt/devicetree.dtb
		if [ $? -ne 0 ];then
			echo "error:Devicetree upgrade faild!"
			cp /mnt/devicetree.dtb.bak /mnt/devicetree.dtb
		fi
		
		mv /mnt/uImage /mnt/uImage.bak
		wget -c "${server}V$version_m.$version_s/uImage" -O /mnt/uImage
		if [ $? -ne 0 ];then
			echo "error:Image upgrade faild!"
			cp /mnt/uImage.bak /mnt/uImage
		fi

		echo "System will reboot right now!"
		exit 0
        # reboot
	fi
	echo "Abort."
else
	echo "Current driver is the newest!"
fi

